package com.fyzk.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Point;
import android.graphics.Shader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.App;
import com.tyjc.lottery.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Utils {

    // 为每一个groupactivity中的子页面设置index,每一个页面对应一个index;
    public static int currentTabIndex = 0;
    public final static int TAB_INDEX_SEARCH = 0;
    public final static int TAB_INDEX_ORDER = 1;
    public final static int TAB_INDEX_HOTAL = 2;
    public final static int TAB_INDEX_ACCOUNT = 3;
    public final static int TAB_INDEX_MORE = 4;

    public static ProgressDialog progressDialog = null;

    private static IPopLisrener mLisrenerPop;

    /**
     * 判断网络
     *
     * @param mActivity
     * @return
     */
    public static boolean isNetworkAvailable(Activity mActivity) {
        // return true;
        Context context = App.getContext();
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private static long lastClickTime;

    /**
     * 是否是快速两次点击
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 800) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 获得屏幕高宽
     *
     * @param activity
     * @return
     */
    public static Point getScreenPoint(Activity activity) {
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Point point = new Point(display.getWidth(), display.getHeight());
        return point;
    }

    /**
     * 得到高
     *
     * @param a
     * @return
     */
    public static int getsW(Activity a) {
        return getScreenPoint(a).x;
    }

    /**
     * 得到宽
     *
     * @param a
     * @return
     */
    public static int getsH(Activity a) {
        return getScreenPoint(a).y;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    @Deprecated
    public static int dp2px(Activity context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Activity context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    // 隐藏软键盘
    public static void hiddenKeyboard(Activity activity) {
        ((InputMethodManager) activity
                .getSystemService(Activity.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    /**
     * 分享 *
     */
    public static void share(Activity mActivity, String text) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        intent.putExtra(Intent.EXTRA_TEXT, text);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mActivity.startActivity(Intent.createChooser(intent,
                mActivity.getTitle()));
    }

    /**
     * 拨打电话
     *
     * @param phonenumber
     */
    public static void tel(Activity a, String phonenumber) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        if (phonenumber != null) {
            phonenumber = phonenumber.replace(",", "");
            phonenumber = phonenumber.replace("，", "");
        }
        intent.setData(Uri.parse("tel:" + phonenumber));
        a.startActivity(intent);
    }

    /* 验证手机号是否合法 */
    public static boolean checkPhone(String phone) {
        // ^(13|15|18)\\d{9}$
        Pattern pattern = Pattern.compile("^(13|14|15|18|17)\\d{9}$");
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    /**
     * 是否是正确的邮件地址
     *
     * @param strEmail
     * @return
     */
    public static boolean isEmail(String strEmail) {
        Pattern pattern = Pattern
                .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(" +
                        "([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        Matcher mc = pattern.matcher(strEmail);
        return mc.matches();
    }

    /**
     * 验证固定电话号码
     *
     * @param strPhone
     * @return
     */
    public static boolean isPhone(String strPhone) {
        boolean tag = true;
        String reg = "^((0\\d{2,3})-)(\\d{7,8})(-(\\d{3,}))?$";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(strPhone);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 验证手机号码
     *
     * @param strMobile
     * @return
     */
    public static boolean isMobile(String strMobile) {
        boolean tag = true;
        String reg = "^(13[0-9]|15[012356789]|17[0-9]|18[02367895]|14[57])[0-9]{8}$"; // 验证手机号码
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(strMobile);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 检查邮编格式
     *
     * @param code
     * @return
     */
    public static boolean isPostcode(String code) {
        boolean tag = true;
        String reg = "^[1-9][0-9]{5}$";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(code);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 身份证
     *
     * @param code
     * @return
     */
    public static boolean isIDCard(String code) {
        boolean tag = true;
        String reg = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(code);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 是否是6到16位字母和数字的结合
     *
     * @param pass
     * @return
     */
    public static boolean isPassWord(String pass) {

        boolean tag = true;
        String reg = "(?![^a-zA-Z0-9]+$)(?![^a-zA-Z/D]+$)(?![^0-9/D]+$).{6,16}$";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(pass);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    // 6-16位 字母 或者数字
    public static boolean isPassWord2(String pass) {

        boolean tag = true;
        String reg = "[0-9a-zA-Z]{6,16}";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(pass);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 是否是ip
     *
     * @param code
     * @return
     */

    public static boolean isIP(String code) {
        if (code.indexOf(":", 5) > 0) {
            code = code.substring(0, code.lastIndexOf(":"));
        }
        boolean tag = true;
        String reg = "^http://(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1," +
				"2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1," +
				"2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(code);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    public static boolean isIP2(String code) {
        if (code.indexOf(":", 5) > 0) {
            code = code.substring(0, code.lastIndexOf(":"));
        }
        boolean tag = true;
        String reg = "^https://(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1," +
				"2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1," +
				"2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
        final Pattern pattern = Pattern.compile(reg);
        final Matcher mat = pattern.matcher(code);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 是否是数子
     *
     * @param str
     * @return
     */

    public static boolean isNum(String str) {
        boolean tag = true;
        tag = str.matches("[0-9]+");
        return tag;
    }

//	public static void share(Activity activity) {
//		AlertDialog.Builder builder = new AlertDialog.Builder(activity,R.style.myDialogStyle);
//		builder.setItems(new String[] { "新浪微博", "腾讯微博", "微信", "QQ" },
//				new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//
//					}
//				});
//		builder.show();
//	}

    public static ArrayList<Activity> activities = new ArrayList<Activity>();

    public static ArrayList<Activity> getActivityList() {
        return activities;
    }

    private static int CircleType = 0;

    public static void SetCircleType(int type) {
        CircleType = type;
    }

    public static int GetCircleType() {
        return CircleType;
    }

    /**
     * @param textView
     */
    public static void setTextGradient(TextView textView) {
        textView.measure(0, 0);
        Shader shader = new LinearGradient(0, 0, 0,
                textView.getMeasuredHeight(), new int[]{
                Color.argb(255, 149, 101, 44),
                Color.argb(255, 210, 185, 105),
                Color.argb(255, 149, 101, 44)}, new float[]{0, 0.3f,
                1f}, Shader.TileMode.CLAMP);
        textView.getPaint().setShader(shader);
    }

    /**
     * Returns application cache directory. Cache directory will be created on
     * SD card <i>("/Android/data/[app_package_name]/cache")</i> if card is
     * mounted. Else - Android defines cache directory on device's file system.
     *
     * @param context Application context
     * @return Cache {@link File directory}
     */
    public static File getCacheDirectory(Context context) {
        File appCacheDir = null;
        if (Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            appCacheDir = getExternalCacheDir(context);
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        return appCacheDir;
    }

    /**
     * 得到缓存路径
     *
     * @param context
     * @return
     */
    private static File getExternalCacheDir(Context context) {
        File dataDir = new File(new File(
                Environment.getExternalStorageDirectory(), context
                .getResources().getString(R.string.app_name)), "data");
        File appCacheDir = new File(
                new File(dataDir, context.getPackageName()), "cache");
        if (!appCacheDir.exists()) {
            if (!appCacheDir.mkdirs()) {
                Log.w("Utility", "Unable to create external cache directory");
                return null;
            }
            try {
                new File(appCacheDir, ".nomedia").createNewFile();
            } catch (IOException e) {
                Log.e("Utility",
                        "Can't create \".nomedia\" file in application external cache directory");
            }
        }
        return appCacheDir;
    }

    /**
     * 用于计算ListView的高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 根据url生成缓存文件完整路径名
     */
    public static String urlToFilePath(String cacheDir, String url) {

        // 扩展名位置
        int index = url.lastIndexOf('.');
        if (index == -1) {
            return null;
        }

        StringBuilder filePath = new StringBuilder();

        // 图片存取路径
        filePath.append(cacheDir).append('/');

        // 图片文件名
        filePath.append(Md5(url)).append(url.substring(index));

        return filePath.toString();
    }

    // MD5変換
    public static String Md5(String str) {
        if (str != null && !str.equals("")) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'a', 'b', 'c', 'd', 'e', 'f'};
                byte[] md5Byte = md5.digest(str.getBytes("UTF8"));
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < md5Byte.length; i++) {
                    sb.append(HEX[(int) (md5Byte[i] & 0xff) / 16]);
                    sb.append(HEX[(int) (md5Byte[i] & 0xff) % 16]);
                }
                str = sb.toString();
            } catch (NoSuchAlgorithmException e) {
            } catch (Exception e) {
            }
        }
        return str;
    }

    /**
     * 从sd卡读取图片
     */
    public static Bitmap readBitMap(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Config.ARGB_8888;
        Bitmap bm = BitmapFactory.decodeFile(path, options);
        // Log.i("get success " + path);
        return bm;
    }

    /**
     * 保存Bitmap到本地
     */
    public static String SaveBitmap(Bitmap bmp, String name) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(name);

            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            // Log.i("save success " + name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return name;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    @Deprecated
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = App.getContext().getResources()
                .getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip转成px
     *
     * @param dpValue
     * @return
     */
    public static int dip2px(float dpValue) {
        float scale = App.getContext().getResources()
                .getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5F);
    }

    /**
     * 验证身份证
     */
    public static boolean checkIdcard(String value) {
        int length = 0;
        if (value == null) {
            return false;
        } else {
            length = value.length();

            if (length != 15) {
            } else if (length != 18) {
            } else {
                return false;
            }
        }
        String[] areasArray = {"11", "12", "13", "14", "15", "21", "22", "23",
                "31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
                "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
                "63", "64", "65", "71", "81", "82", "91"};

        HashSet<String> areasSet = new HashSet<String>(
                Arrays.asList(areasArray));
        String valueStart2 = value.substring(0, 2);

        if (areasSet.contains(valueStart2)) {
        } else {
            return false;
        }

        Pattern pattern = null;
        Matcher matcher = null;

        int year = 0;
        switch (length) {
            case 15:
                year = Integer.parseInt(value.substring(6, 8)) + 1900;

                if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0)) {
                    pattern = Pattern
                            .compile("^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)" +
									"(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)" +
									"(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"); //
					// 测试出生日期的合法性
                } else {
                    pattern = Pattern
                            .compile("^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)" +
									"(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)" +
									"(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$");
					// 测试出生日期的合法性
                }
                matcher = pattern.matcher(value);
                if (matcher.find()) {
                    return true;
                } else {
                    return false;
                }
            case 18:
                year = Integer.parseInt(value.substring(6, 10));

                if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0)) {
                    pattern = Pattern
                            .compile("^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)" +
									"(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)" +
									"(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))" +
									"[0-9]{3}[0-9Xx]$"); // 测试出生日期的合法性
                } else {
                    pattern = Pattern
                            .compile("^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)" +
									"(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)" +
									"(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))" +
									"[0-9]{3}[0-9Xx]$"); // 测试出生日期的合法性
                }

                matcher = pattern.matcher(value);
                if (matcher.find()) {
                    int S = (Integer.parseInt(value.substring(0, 1)) + Integer
                            .parseInt(value.substring(10, 11)))
                            * 7
                            + (Integer.parseInt(value.substring(1, 2)) + Integer
                            .parseInt(value.substring(11, 12)))
                            * 9
                            + (Integer.parseInt(value.substring(2, 3)) + Integer
                            .parseInt(value.substring(12, 13)))
                            * 10
                            + (Integer.parseInt(value.substring(3, 4)) + Integer
                            .parseInt(value.substring(13, 14)))
                            * 5
                            + (Integer.parseInt(value.substring(4, 5)) + Integer
                            .parseInt(value.substring(14, 15)))
                            * 8
                            + (Integer.parseInt(value.substring(5, 6)) + Integer
                            .parseInt(value.substring(15, 16)))
                            * 4
                            + (Integer.parseInt(value.substring(6, 7)) + Integer
                            .parseInt(value.substring(16, 17)))
                            * 2
                            + Integer.parseInt(value.substring(7, 8))
                            * 1
                            + Integer.parseInt(value.substring(8, 9))
                            * 6
                            + Integer.parseInt(value.substring(9, 10)) * 3;
                    int Y = S % 11;
                    String M = "F";
                    String JYM = "10X98765432";
                    M = JYM.substring(Y, Y + 1); // 判断校验位
                    if (M.equals(value.substring(17, 18))) {
                        return true; // 检测ID的校验位
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            default:
                return false;
        }
    }
//
//	/**
//	 * 启动首页
//	 * 
//	 * @param mContext
//	 * @param data
//	 *            传递数据 void
//	 */
//	public static void startMainActivity(Context mContext, Intent data) {
//		Intent intent = new Intent(mContext, HomeMainActivity.class);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//		if (data != null) {
//			intent.putExtras(data);
//		}
//
//		mContext.startActivity(intent);
//	}

//	/**
//	 * 启动首页
//	 * 
//	 * @param mContext
//	 *            void
//	 */
//	public static void startMainActivity(Context mContext) {
//		startMainActivity(mContext, null);
//	}
//
//	/**
//	 * 显示弹出下拉列表框
//	 * 
//	 * @param context
//	 * @param anchorView
//	 * @param adapter
//	 * @param textView
//	 * @param yoff
//	 * @param mode
//	 */
//	private static void showPopupWindowList(Activity activity, View anchorView,
//			final List<String> list, final TextView textView, int yoff, int mode) {
//		final PopupWindow popup = new PopupWindow(activity);
//		popup.setWidth(anchorView.getWidth());
//
//		popup.setHeight(LayoutParams.WRAP_CONTENT);
//
//		View contentView;
//		if (mode == 1) {
//			contentView = LayoutInflater.from(activity).inflate(
//					R.layout.l_popupwindow_list1, null);
//		} else if (mode == 2) {
//			contentView = LayoutInflater.from(activity).inflate(
//					R.layout.l_popupwindow_list2, null);
//		} else {
//			contentView = LayoutInflater.from(activity).inflate(
//					R.layout.l_popupwindow_list1, null);
//		}
//		ListView list_lv = (ListView) contentView
//				.findViewById(R.id.lv_popupwindow_list);
//		list_lv.setAdapter(new PopupWindowListAdapter(list, activity, mode));
//		list_lv.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				textView.setValue(list.get(position));
//				if (mLisrenerPop != null) {
//					mLisrenerPop.OnItemClicked(position);
//				}
//				popup.dismiss();
//			}
//		});
//		popup.setContentView(contentView);
//		popup.setBackgroundDrawable(new BitmapDrawable());
//		popup.setFocusable(true);
//		popup.setOutsideTouchable(true);
//		popup.showAsDropDown(anchorView, 0, yoff);
//	}

    public interface IPopLisrener {
        public void OnItemClicked(int pos);
    }

    ;

//	public static void showPopupWindowList1(Activity activity, View anchorView,
//			List<String> list, TextView textView, int yoff) {
//		showPopupWindowList(activity, anchorView, list, textView, yoff, 1);
//	}
//
//	public static void showPopupWindowList2(Activity activity, View anchorView,
//			List<String> list, TextView textView, int yoff,
//			IPopLisrener lisrener) {
//		mLisrenerPop = lisrener;
//		showPopupWindowList(activity, anchorView, list, textView, yoff, 2);
//	}

    final static int BUFFER_SIZE = 4096;

    /**
     * 将InputStream转换成String
     *
     * @param in InputStream
     * @return String
     * @throws Exception
     */
    public static String InputStreamTOString(InputStream in) throws Exception {

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count = -1;
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
            outStream.write(data, 0, count);

        data = null;
        return new String(outStream.toByteArray(), "utf-8");
    }

    /**
     * 获取格式化的当前日期 yyyy-MM-dd HH:mm
     *
     * @return
     */
    public static String getRefreshTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(new Date());
    }

    /**
     * 把数组所有米素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    /**
     * 图片裁剪（3：2）
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    public static void cropImageUri3b2(Activity context, Uri uri,
                                       Uri targetUri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 2);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 图片裁剪（1：1）
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    public static void cropImageUri1b1(Activity context, Uri uri,
                                       Uri targetUri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 讲uri变为bitmap
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap decodeUriAsBitmap(Activity context, Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(context.getContentResolver()
                    .openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    public static String getNowTime(String dateformat) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);// 可以方便地修改日期格式
        String hehe = dateFormat.format(now);
        return hehe;
    }
//
//	/**
//	 * 判断当前用户是否为创业者或商家
//	 * 
//	 * @return
//	 */
//	public static boolean isOpenShop() {
//		if (MyApplication.getUser() != null) {
//			if (Constants.USER_TYPE_ENTREPRENEUR.equals(MyApplication.getUser()
//					.getType())
//					|| Constants.USER_TYPE_STORE.equals(MyApplication.getUser()
//							.getType())) {
//				return true;
//			}
//		}
//		return false;
//	}


//	public static void showClearShoppingcartDialog(Context context) {
//		new AlertDialog.Builder(context,
//				R.style.myDialogStyle).setTitle("提示")
//				.setMessage(R.string.add_goods_error)
//				.setNegativeButton("取消", new OnClickListener() {
//					
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						// TODO Auto-generated method stub
//						dialog.dismiss();
//					}
//				}).setPositiveButton("确认", new OnClickListener() {
//					
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						// TODO Auto-generated method stub
//						dialog.dismiss();
//						if(null != ShoppingCartUtil.getInstance().listener){
//							ShoppingCartUtil.getInstance().listener.clearShoppingcart();
//						}else{
//							AppToast.getToast().show("具有添加购物车的页面要注册ShoppingCartUtil.getInstance().ClearShoppingcartListener事件！");
//						}
//					}
//				}).show();
//	}

    /**
     * 判断当前时间与第一次登陆是否超过7天
     *
     * @param curTime
     * @param oldTime
     * @return
     */
    public static boolean getDateDiff(long curTime, long oldTime) {
        long dis = curTime - oldTime;
        long disH = dis / 1000 / 60 / 60;
        int hours = 24 * 7;
        if (disH >= hours) {
            return true;
        }
        return false;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp,
                                        final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    public static void toggleSoftwareboard() {
        InputMethodManager imm = (InputMethodManager) App.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); //得到InputMethodManager的实例
//		if (imm.isActive()) {//如果开启
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
//		}

    }

    /**
     * 小数点后保留两位
     * @param price
     */
    public static String getPrice(String price) {
        DecimalFormat format = new DecimalFormat("0.00");
        String a = "0.00";
        try {
            a= format.format(new BigDecimal(price.replace(",", "")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }

    public static void showToast(Context context , String msg, BaseActivity activity){

        if (context == null || msg == null || "".equals(msg))
            return;
        if(!isNetworkAvailable(activity)) {
            Toast.makeText(context, "无网络连接，请先打开网络连接", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 检测String是否全是中文
     * @param name
     * @return
     */
    public static boolean checkNameChese(String name){
        boolean res=true;
        char [] cTemp = name.toCharArray();
        for(int i=0;i<name.length();i++)
        {
            if(!isChinese(cTemp[i]))
            {
                res=false;
                break;
            }
        }
        return res;
    }

    /**
     * 判定输入汉字
     * @param c
     * @return
     */
    public static  boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 正则：身份证号码18位
     */
    public static final String REGEX_IDCARD18 = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
    public static boolean isIDcard18(String a){
        if (a.matches(REGEX_IDCARD18)){
            return  true;
        }else {
            return false;
        }

    }

    /**
     * 判断字符串是否全部为中文字符组成
     * @param str	检测的文字
     * @return	true：为中文字符串，false:含有非中文字符
     */
    public static boolean isChineseStr(String str){
        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
        char c[] = str.toCharArray();
        for(int i=0;i<c.length;i++){
            Matcher matcher = pattern.matcher(String.valueOf(c[i]));
            if(!matcher.matches()){
                return false;
            }
        }
        return true;
    }

}
